import React, { useState, useEffect } from 'react';
import { useGameStore } from '../store/gameStore';
import { SkillType } from '../systems/SkillSystem';
import { Position } from '../types/game';
import { Flame, Shield, Zap, Target } from 'lucide-react';

interface SkillPanelProps {
  onSkillSelect?: (skillType: SkillType) => void;
  selectedSkill?: SkillType | null;
}

const SkillPanel: React.FC<SkillPanelProps> = ({ onSkillSelect, selectedSkill }) => {
  const { 
    gameState, 
    getAllSkillsStatus, 
    useSkill, 
    addSkillEnergy 
  } = useGameStore();
  
  const [skillsStatus, setSkillsStatus] = useState<any>(null);
  const [showTargeting, setShowTargeting] = useState<SkillType | null>(null);

  // 更新技能状态
  useEffect(() => {
    const updateStatus = () => {
      const status = getAllSkillsStatus();
      setSkillsStatus(status);
    };

    updateStatus();
    const interval = setInterval(updateStatus, 100); // 每100ms更新一次

    return () => clearInterval(interval);
  }, [getAllSkillsStatus]);

  // 技能配置
  const skillConfigs = {
    fireAttack: {
      name: '火攻',
      description: '对指定区域造成持续火焰伤害',
      icon: Flame,
      color: 'text-red-500',
      bgColor: 'bg-red-100',
      borderColor: 'border-red-300',
      needsTarget: true
    },
    reinforcement: {
      name: '援军',
      description: '临时召唤锐士方阵阻挡敌人',
      icon: Shield,
      color: 'text-blue-500',
      bgColor: 'bg-blue-100',
      borderColor: 'border-blue-300',
      needsTarget: true
    },
    inspire: {
      name: '激将',
      description: '提升全体友军攻击力和攻击速度',
      icon: Zap,
      color: 'text-yellow-500',
      bgColor: 'bg-yellow-100',
      borderColor: 'border-yellow-300',
      needsTarget: false
    }
  };

  // 处理技能点击
  const handleSkillClick = (skillType: SkillType) => {
    if (!skillsStatus || !skillsStatus[skillType]) return;
    
    const status = skillsStatus[skillType];
    const config = skillConfigs[skillType];
    
    if (!status.canUse) {
      // 显示不能使用的原因
      console.log(`技能不可用: ${status.reason}`);
      return;
    }
    
    if (config.needsTarget) {
      // 需要目标的技能，进入瞄准模式
      setShowTargeting(skillType);
      if (onSkillSelect) {
        onSkillSelect(skillType);
      }
    } else {
      // 不需要目标的技能，直接使用
      const result = useSkill(skillType);
      if (result.message) {
        console.log(result.message);
      }
    }
  };

  // 处理目标选择
  const handleTargetSelect = (position: Position) => {
    if (!showTargeting) return;
    
    const result = useSkill(showTargeting, position);
    if (result.message) {
      console.log(result.message);
    }
    
    setShowTargeting(null);
    if (onSkillSelect) {
      onSkillSelect(null);
    }
  };

  // 取消瞄准
  const cancelTargeting = () => {
    setShowTargeting(null);
    if (onSkillSelect) {
      onSkillSelect(null);
    }
  };

  // 渲染技能按钮
  const renderSkillButton = (skillType: SkillType) => {
    const config = skillConfigs[skillType];
    const status = skillsStatus?.[skillType];
    const Icon = config.icon;
    
    if (!status) return null;
    
    const isSelected = selectedSkill === skillType;
    const canUse = status.canUse;
    const energyPercent = status.energyPercent;
    
    return (
      <div key={skillType} className="relative">
        {/* 技能按钮 */}
        <button
          onClick={() => handleSkillClick(skillType)}
          disabled={!canUse}
          className={`
            relative w-16 h-16 rounded-lg border-2 transition-all duration-200
            ${isSelected ? 'ring-2 ring-purple-400' : ''}
            ${canUse 
              ? `${config.bgColor} ${config.borderColor} hover:scale-105 cursor-pointer` 
              : 'bg-gray-100 border-gray-300 cursor-not-allowed opacity-50'
            }
          `}
        >
          {/* 技能图标 */}
          <Icon 
            className={`w-8 h-8 mx-auto ${canUse ? config.color : 'text-gray-400'}`} 
          />
          
          {/* 能量进度条 */}
          <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-200 rounded-b-lg overflow-hidden">
            <div 
              className={`h-full transition-all duration-300 ${
                energyPercent >= 100 ? 'bg-green-400' : 'bg-blue-400'
              }`}
              style={{ width: `${energyPercent}%` }}
            />
          </div>
          
          {/* 冷却时间显示 */}
          {status.cooldownRemaining > 0 && (
            <div className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-50 rounded-lg">
              <span className="text-white text-xs font-bold">
                {status.cooldownRemaining}s
              </span>
            </div>
          )}
        </button>
        
        {/* 技能信息提示 */}
        <div className="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 opacity-0 hover:opacity-100 transition-opacity duration-200 pointer-events-none z-10">
          <div className="bg-gray-800 text-white text-xs rounded px-2 py-1 whitespace-nowrap">
            <div className="font-semibold">{config.name}</div>
            <div className="text-gray-300">{config.description}</div>
            <div className="text-gray-400">
              能量: {Math.floor(energyPercent)}%
              {status.cooldownRemaining > 0 && ` | 冷却: ${status.cooldownRemaining}s`}
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (!skillsStatus) {
    return (
      <div className="bg-white rounded-lg shadow-md p-4">
        <div className="text-gray-500 text-center">技能系统加载中...</div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-lg shadow-md p-4">
      {/* 面板标题 */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-semibold text-gray-800">计策技能</h3>
        <div className="text-sm text-gray-600">
          棋魂: {gameState.chessSpirit}
        </div>
      </div>
      
      {/* 技能按钮组 */}
      <div className="flex space-x-3 justify-center">
        {renderSkillButton('fireAttack')}
        {renderSkillButton('reinforcement')}
        {renderSkillButton('inspire')}
      </div>
      
      {/* 瞄准模式提示 */}
      {showTargeting && (
        <div className="mt-4 p-3 bg-purple-100 border border-purple-300 rounded-lg">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Target className="w-4 h-4 text-purple-600" />
              <span className="text-sm text-purple-800">
                选择 {skillConfigs[showTargeting].name} 的目标位置
              </span>
            </div>
            <button
              onClick={cancelTargeting}
              className="text-xs text-purple-600 hover:text-purple-800 underline"
            >
              取消
            </button>
          </div>
        </div>
      )}
      
      {/* 开发模式：快速充能按钮 */}
      {process.env.NODE_ENV === 'development' && (
        <div className="mt-4 pt-4 border-t border-gray-200">
          <div className="text-xs text-gray-500 mb-2">开发模式</div>
          <div className="flex space-x-2">
            <button
              onClick={() => addSkillEnergy('fireAttack', 100)}
              className="px-2 py-1 text-xs bg-red-100 text-red-600 rounded hover:bg-red-200"
            >
              充能火攻
            </button>
            <button
              onClick={() => addSkillEnergy('reinforcement', 80)}
              className="px-2 py-1 text-xs bg-blue-100 text-blue-600 rounded hover:bg-blue-200"
            >
              充能援军
            </button>
            <button
              onClick={() => addSkillEnergy('inspire', 60)}
              className="px-2 py-1 text-xs bg-yellow-100 text-yellow-600 rounded hover:bg-yellow-200"
            >
              充能激将
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default SkillPanel;